<?php
namespace app\controller\model;

use app\BaseController;
use app\controller\model\JSSDK;
use app\controller\model\Config;
use think\facade\Db;
use think\facade\Session;
class Code extends BaseController
{
    public $mobile="";
    public $code="";
    public $ctype=0;
    protected $addtime='';
    protected $endtime='';
    protected $lastTime=60;//相同手机号相同ctype间隔时间才能写入或读取
    protected $cTime=300;//有效时间
    public function __construct($mobile='',$code='',$ctype=1){
        $this->mobile = $mobile ;
        $this->code = $code ;
        $this->ctype = $ctype ;
        $this->addtime = date("Y-m-d H:i:s");
        $this->endtime = date("Y-m-d H:i:s",time()+$this->cTime);
        if($code==''){
            $this->code = rand(1000,9999);
//            $this->code = 1111;
        }
    }
    public function wCode(){
        $upArr=['mobile'=>$this->mobile,'code'=>$this->code,'ctype'=>$this->ctype,'addtime'=>$this->addtime,'endtime'=>$this->endtime];
        $check = $this->checkCode(1);
        if(!$check){
            return -1;
        }
        $re = DB::name("code")->insertGetId($upArr);
        if($re){
            return $this->code;
        }
        return false;
    }
    public function rCode(){
        //检查验证码是否有效
        return $this->checkCode(2);
    }
    protected function checkCode($cint=1){
        if($cint==1){
            //检查是否在lastTime内重复获取验证码
            $re = DB::name("code")->where("mobile",$this->mobile)->where("ctype",$this->ctype)->order("id desc")->find();
            if($re && $re['addtime'] > date("Y-m-d H:i:s",time()-$this->lastTime)){
                return false;
            }
            return true;
        }
        elseif ($cint==2){
            //检查验证码是否有效
            $re = DB::name("code")->where("mobile",$this->mobile)->where("ctype",$this->ctype)->where("code",$this->code)->order("id desc")->find();
            if($re && $re['endtime'] < $this->addtime){
                return false;
            }
            return true;
        }
        return false;
    }
}
?>